from flask import Flask, session, g
from flask_migrate import Migrate
import config
from exts import db, mail, redis
from blueprints import user, qa, index
from models import User

app = Flask(__name__)
app.config.from_object(config) # 加载配置文件

db.init_app(app) # 初始化数据库
mail.init_app(app) # 初始化邮箱
redis.init_app(app) # 初始化redis
migrate = Migrate(app, db) # 初始化迁移
# 注册蓝图
app.register_blueprint(user.bp)
app.register_blueprint(qa.bp)
app.register_blueprint(index.bp)

# hook
@app.before_request # 请求之前执行
def before_request():
    user_id = session.get('user_id')
    setattr(g, 'user', None)
    if user_id:
        user = User.query.get(user_id)
        setattr(g, 'user', user)
@app.context_processor # 上下文处理器
def context_processors():
    return {'user': g.user}

if __name__ == '__main__':
    app.run()